package com.zhfi.dataapply.schedule.writer.chaincode;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zhfi.dataapply.entity.data.po.chaincode.CompanyPagePO;
import com.zhfi.dataapply.entity.data.po.chaincode.IpoDataPO;
import com.zhfi.dataapply.entity.data.vo.chaincode.CompanyPageVO;
import com.zhfi.dataapply.mapper.chaincode.IpoDataMapper;
import com.zhfi.dataapply.mapper.ipofinance.CompanyPageMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Slf4j
@Component
public class CompanyPageWriter implements ItemWriter<CompanyPageVO> {

    @Autowired
    private CompanyPageMapper companyPageMapper;

    @Autowired
    private IpoDataMapper ipoDataMapper;

    @Override
    public void write(List<? extends CompanyPageVO> list) throws Exception {
        for (CompanyPageVO vo : list) {
            try {
                CompanyPagePO companyPagePO = new CompanyPagePO();
                BeanUtils.copyProperties(vo, companyPagePO);
                UpdateWrapper<CompanyPagePO> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("company_id", companyPagePO.getCompanyId());
                updateWrapper.eq("chain_code", companyPagePO.getChainCode());
                int count = companyPageMapper.update(companyPagePO, updateWrapper);
                if (count <= 0) {
                    companyPageMapper.insert(companyPagePO);
                }
                List<IpoDataPO> ipoData = vo.getIpoData();
                if (!CollectionUtils.isEmpty(ipoData)) {
                    ipoData.forEach(po -> {
                        po.setCompanyId(vo.getCompanyId());
                        UpdateWrapper<IpoDataPO> wrapper = new UpdateWrapper<>();
                        wrapper.eq("company_id", po.getCompanyId());
                        wrapper.eq("ipo_type", po.getIpoType());
                        if (ipoDataMapper.update(po, wrapper) <= 0 ) {
                            ipoDataMapper.insert(po);
                        }
                    });
                }
            } catch (Exception e) {
                log.error("CompanyPageWriter写入数据失败：" + vo, e);
            }
        }
    }
}
